package me.zhengjie.modules.website.controller;

import me.zhengjie.modules.website.dto.ApiResponse;
import me.zhengjie.modules.website.service.ColumnTableService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.domain.Page;
import org.springframework.data.domain.PageRequest;
import org.springframework.format.annotation.DateTimeFormat;
import org.springframework.http.HttpStatus;
import org.springframework.http.ResponseEntity;
import io.swagger.annotations.ApiOperation;
import io.swagger.annotations.Api;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.validation.annotation.Validated;
import org.springframework.web.bind.annotation.*;
import me.zhengjie.modules.website.domain.ContentTable;
import me.zhengjie.modules.website.service.ContentTableService;
import org.springframework.data.domain.Pageable;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.DeleteMapping;
import org.springframework.web.bind.annotation.PutMapping;
import org.springframework.web.bind.annotation.GetMapping;
import me.zhengjie.modules.website.domain.PageResult;

import java.time.LocalDateTime;
import java.util.Date;
import java.util.List;

/**
 * @author system
 * @since 2024-09-26 16:41:54
 */
@RestController
@RequestMapping("/api/contentTable")
@Api(tags = " 网页-内容管理")
public class ContentTableController {

    @Autowired
    private ContentTableService contentTableService;

    @Autowired
    private ColumnTableService columnTableService;





    /**
     * 分页查询
     *
     * @param params
     * @param startDate 起始时间
     * @param endDate   结束时间
     * @return
     */
    @ApiOperation(value = "分页查询", notes = "分页查询", produces = "application/json")
    @PostMapping("/website/findPage")
    public ResponseEntity<PageResult<ContentTable>> findPage(
            @RequestBody ContentTable params,
            @RequestParam(required = false) @DateTimeFormat(pattern = "yyyy-MM-dd HH:mm:ss") LocalDateTime startDate,
            @RequestParam(required = false) @DateTimeFormat(pattern = "yyyy-MM-dd HH:mm:ss") LocalDateTime endDate,
            Pageable pageable) {

        // 调用服务层方法执行分页查询
        PageResult<ContentTable> result = contentTableService.findPage(params, startDate, endDate, pageable);
        return new ResponseEntity<>(result, HttpStatus.OK);
    }


    /**
     * 列表查询
     *
     * @return
     */
    @ApiOperation(value = "根据columnID分页查询", notes = "根据columnID分页查询", produces = "application/json")
    @PostMapping("/website/findPageByColumn")
    public ResponseEntity<PageResult<ContentTable>> findPageByColumn(
            @RequestBody ContentTable contentTable,
            @RequestParam(required = false) @DateTimeFormat(pattern = "yyyy-MM-dd HH:mm:ss") LocalDateTime startDate,
            @RequestParam(required = false) @DateTimeFormat(pattern = "yyyy-MM-dd HH:mm:ss") LocalDateTime endDate,
            Pageable pageable) {

        // 调用服务层方法执行分页查询
        PageResult<ContentTable> result = contentTableService.findLikeColumnId(contentTable, startDate, endDate, pageable);
        return new ResponseEntity<>(result, HttpStatus.OK);
    }


    /**
     * 列表查询
     *
     * @param params
     * @return
     */
    @ApiOperation(value = "列表查询", notes = "列表查询", produces = "application/json")
    @PostMapping("/website/findList")
    public ResponseEntity<List<ContentTable>> findList(@RequestBody ContentTable params) {
        List<ContentTable> result = contentTableService.findList(params);
        return new ResponseEntity<>(result, HttpStatus.OK);

    }

    @ApiOperation(value = "根据栏目id，前端传入排序条件分页查询", notes = "根据栏目id，前端传入排序条件分页查询", produces = "application/json")
    @GetMapping("/website/columnToTile")
    public Page<ContentTable> searchByColumnIdsPagedToTitle(
            @RequestParam(required = false) String columnIds, Pageable pageable) {
        return contentTableService.getContentsByColumnIdsToTile(columnIds, pageable);
    }


    /**
     * 根据栏目id进行内容查询
     * @return 内容列表
     */
    @ApiOperation(value = "根据栏目id进行内容查询", notes = "根据栏目id进行内容查询", produces = "application/json")
    @GetMapping("/website/column")
    public Page<ContentTable> searchByColumnIdsPaged(
            @RequestParam(required = false) String columnIds, Pageable pageable) {
        return contentTableService.getContentsByColumnIds(columnIds, pageable);
    }

    /**
     * 根据栏目id数组进行内容查询
     * @return 内容列表
     */
    @ApiOperation(value = "根据栏目id数组进行内容查询", notes = "根据栏目id数组进行内容查询", produces = "application/json")
    @GetMapping("/website/columnArray")
    public Page<ContentTable> searchByColumnArrayPaged(
            @RequestParam(required = false) String[] columnIds, Pageable pageable) {
        return contentTableService.getContentsByColumnArray(columnIds, pageable);
    }


    /**
     * 查询
     *
     * @param id
     * @return
     */
    @ApiOperation(value = "查询", notes = "查询详情")
    @GetMapping("/website/findById/{id}")
    public ResponseEntity<ContentTable> findById(@PathVariable("id") Long id) {
        ContentTable contentTable = contentTableService.findById(id);
        return new ResponseEntity<>(contentTable, HttpStatus.OK);

    }

    /**
     * 新增
     *
     * @param contentTable
     * @return
     */
    @ApiOperation(value = "新增", notes = "新增数据")
    @PostMapping("/insert")
    public ResponseEntity<String> insert(@Validated @RequestBody ContentTable contentTable) {
        try {
            ContentTable savedContent = contentTableService.addContent(contentTable);
            return new ResponseEntity<>("Successful", HttpStatus.OK);
        } catch (IllegalArgumentException e) {
            // 单文档内容特定错误
            return new ResponseEntity<>("新增的是单文档内容，且该栏目已有发布内容", HttpStatus.CONFLICT);
        } catch (Exception e) {
            // 其他错误
            return new ResponseEntity<>("服务器错误！", HttpStatus.INTERNAL_SERVER_ERROR);
        }
    }

    /**
     * 修改
     *
     * @param contentTable
     * @return
     */
    @ApiOperation(value = "修改", notes = "修改数据")
    @PutMapping("/update")
    public ResponseEntity<ContentTable> update(@Validated @RequestBody ContentTable contentTable) {
        ContentTable result = contentTableService.update(contentTable);
        return new ResponseEntity<>(result, HttpStatus.OK);

    }

    /**
     * 删除
     *
     * @param id
     * @return
     */
    @ApiOperation(value = "删除", notes = "删除数据")
    @DeleteMapping("/del/{id}")
    public ResponseEntity<String> delete(@PathVariable("id") Long id) {
        contentTableService.delete(id);
        return new ResponseEntity<>("Successful", HttpStatus.OK);

    }

    /**
     * 增加内容浏览量
     *
     * @param contentId
     * @return
     */
    @Transactional
    @ApiOperation(value = "增加内容浏览量", notes = "通过内容ID增加浏览量")
    @PostMapping("/website/incrementViewCount/{contentId}")
    public ResponseEntity<String> incrementViewCount(@PathVariable Long contentId) {
        contentTableService.incrementViewCount(contentId);
        return new ResponseEntity<>("Successful", HttpStatus.OK);

    }

    /**
     * 增加内容点赞量
     *
     * @param contentId
     * @return
     */
    @Transactional
    @ApiOperation(value = "增加内容点赞量", notes = "通过内容ID增加点赞量")
    @PostMapping("/website/incrementLikeCount/{contentId}")
    public ResponseEntity<String> incrementLikeCount(@PathVariable Long contentId) {
        contentTableService.incrementLikeCount(contentId);
        return new ResponseEntity<>("Successful", HttpStatus.OK);

    }

    /**
     * 根据title模糊查询内容
     *
     * @param title
     * @param page
     * @param size
     * @return
     */
    @ApiOperation(value = "展示平台-根据title模糊查询内容", notes = "展示平台-根据title模糊查询内容")
    @GetMapping("/website/search")
    public ResponseEntity<Page<ContentTable>> searchContentByTitle(
            @RequestParam String title,
            @RequestParam(defaultValue = "0") int page,
            @RequestParam(defaultValue = "10") int size) {

        PageRequest pageRequest = PageRequest.of(page, size);
        Page<ContentTable> contentPage = contentTableService.searchByTitle(title, pageRequest);

        return new ResponseEntity<>(contentPage, HttpStatus.OK);
    }

    @ApiOperation("发布待发布内容")
    @PostMapping("/publish/{id}")
    public ResponseEntity<String> publishContent(
            @PathVariable Long id,
            @RequestParam(required = false) @DateTimeFormat(pattern = "yyyy-MM-dd HH:mm:ss") Date releaseTime) {
        try {
            contentTableService.publishContent(id, releaseTime);
            return ResponseEntity.ok("Successful");
        } catch (Exception e) {
            return ResponseEntity.status(HttpStatus.INTERNAL_SERVER_ERROR)
                    .body("Content publication failed：" + e.getMessage());
        }
    }

    @ApiOperation("撤销已发布内容")
    @PostMapping("/revoke/{id}")
    public ResponseEntity<String> revokeContent(
            @PathVariable Long id) {
        try {
            contentTableService.revokeContent(id);
            return ResponseEntity.ok("撤销成功！");
        } catch (Exception e) {
            return ResponseEntity.status(HttpStatus.INTERNAL_SERVER_ERROR)
                    .body("Content publication failed：" + e.getMessage());
        }
    }

    @ApiOperation(value = "展示平台-根据栏目及标题模糊查询内容", notes = "递归获取栏目子级，分页查询内容")
    @GetMapping("/website/searchByColumnAndTitle")
    public ResponseEntity<Page<ContentTable>> searchContentByColumnAndTitle(
            @RequestParam Long columnId,
            @RequestParam(required = false, defaultValue = "") String title,
            @RequestParam(defaultValue = "0") int page,
            @RequestParam(defaultValue = "10") int size) {

        Pageable pageable = PageRequest.of(page, size);
        Page<ContentTable> contentPage = contentTableService.searchByColumnAndTitle(columnId, title, pageable);

        return new ResponseEntity<>(contentPage, HttpStatus.OK);
    }


    /**
     * 更新内容信息
     *
     * @param contentTable 更新的内容信息
     * @return 更新后的内容
     */
    @PutMapping("/updateContent")
    @ApiOperation(value = "Update content", notes = "更新内容信息，包括标题、栏目、状态等")
    public ResponseEntity<Object> updateContent(@RequestBody ContentTable contentTable) {

        try {
            // 调用服务层的更新方法
            ContentTable updatedContent = contentTableService.updateContent(contentTable);
            // 返回更新后的内容信息
            return ResponseEntity.ok(updatedContent);
        } catch (IllegalArgumentException e) {
            // 特殊的业务异常，如栏目已存在内容等
            return new ResponseEntity<>("修改的内容栏目是单文档内容，且该栏目已有发布内容", HttpStatus.CONFLICT);
        } /*catch (RuntimeException e) {
            // 捕获异常并返回失败响应
            return new ResponseEntity<>("服务器错误！", HttpStatus.CONFLICT);
        }*/
    }





}
